<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form :model="formModel"
               :rules="formRules"
               ref="formRef"
               label-width="150px">
        <el-form-item label="推荐服务种类："
                      prop="serveId">
          <el-select v-model="formModel.serveId"
                     placeholder="请选择推荐服务种类"
                     @change="changeType"
                     :disabled="isEdit">
            <el-option v-for="item in typeList"
                       :key="item.serveId"
                       :label="item.name"
                       :value="item.serveId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片："
                      prop="imageUrl"
                      class="mt-20">
          <el-upload class="avatar-uploader"
                     :action="uploadImgUrl"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="formModel.imageUrl"
                 :src="formModel.imageUrl"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序："
                      prop="sortNum">
          <el-input-number placeholder="请输入排序"
                           v-model="formModel.sortNum"
                           :min="1"
                           :precision="0"
                           type="number"
                           :controls="false"
                           class="w-200">
          </el-input-number>
        </el-form-item>
        <!-- 健康风险(筛查) S -->
        <el-form-item label="推荐子类："
                      prop="sonTypeIds"
                      v-if="currTypeIndex === 1">
          <el-select v-model="formModel.sonTypeIds"
                     multiple
                     filterable
                     allow-create
                     placeholder="请选择推荐子类"
                     @change="changeChildType">
            <el-option v-for="item in childTypeList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推荐服务："
                      v-if="currTypeIndex === 1">
          <el-table border
                    :data="tableData"
                    tooltip-effect="highLight"
                    style="width: 100%">
            <el-table-column label="全选"
                             align="center"
                             prop="apply"
                             width="55">
              <template slot="header"
                        slot-scope="scope">
                <el-checkbox v-model="checkAll"
                             :indeterminate="tableIsIndeterminate"
                             @change="handleChange"></el-checkbox>
              </template>
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.apply"
                             :true-label="1"
                             :false-label="0"
                             @change="tableCheckboxChange(scope.row)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="子类名称"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sonServeName"
                          class="layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="服务名称"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.serviceName"
                          class="layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>

          </el-table>
        </el-form-item>
        <!-- 健康风险(筛查) E -->
        <!-- 私人医生(筛查) 、家庭医生(筛查) S-->
        <el-form-item label="服务包选择："
                      v-if="currTypeIndex === 3 || currTypeIndex === 4">
          <el-table border
                    :data="tableData"
                    tooltip-effect="dark"
                    style="width: 100%">
            <el-table-column label="全选"
                             align="center"
                             prop="apply"
                             width="55">
              <template slot="header"
                        slot-scope="scope">
                <el-checkbox v-model="checkAll"
                             :indeterminate="tableIsIndeterminate"
                             @change="handleChange"></el-checkbox>
              </template>
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.apply"
                             :true-label="1"
                             :false-label="0"
                             @change="tableCheckboxChange(scope.row)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="服务包名称"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.serveName"
                          class=" layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="带队专家"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.doctorName"
                          class="layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="所属科室"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.departmentName"
                          class="w-200 layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="所属医院"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.hospitalName"
                          class="w-200 layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <!-- 私人医生、家庭医生 E-->
        <!-- 医院体检、门诊快检 S -->
        <el-form-item label="推荐医院："
                      prop="hospitalId"
                      v-if="currTypeIndex === 2 || currTypeIndex === 5">
          <el-select v-model="formModel.sonTypeIds"
                     multiple
                     placeholder="请选择推荐医院"
                     @change="changeChildType">
            <el-option v-for="item in childTypeList"
                       :key="item.hospitalId"
                       :label="item.name"
                       :value="item.hospitalId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推荐服务："
                      v-if="currTypeIndex === 2 || currTypeIndex === 5">
          <el-table border
                    :data="tableData"
                    tooltip-effect="highLight"
                    ref="multipleTable"
                    style="width: 100%">
            <el-table-column label="全选"
                             align="center"
                             prop="apply"
                             width="55">
              <template slot="header"
                        slot-scope="scope">
                <el-checkbox v-model="checkAll"
                             :indeterminate="tableIsIndeterminate"
                             @change="handleChange"></el-checkbox>
              </template>
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.apply"
                             :true-label="1"
                             :false-label="0"
                             @change="tableCheckboxChange(scope.row)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="医院名称"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.hospitalName"
                          class="layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="体检名称"
                             align="center"
                             v-if="currTypeIndex === 2">
              <template slot-scope="scope">
                <el-input v-model="scope.row.serveName"
                          class="layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="门诊快诊"
                             align="center"
                             v-if="currTypeIndex === 5">
              <template slot-scope="scope">
                <el-input v-model="scope.row.serveName"
                          class="layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <!-- 医院体检、门诊快检 E -->
        <!-- 智能穿戴设备 S-->
        <el-form-item label="服务包选择："
                      v-if="currTypeIndex === 6">
          <el-table border
                    :data="tableData"
                    tooltip-effect="dark"
                    style="width: 50%">
            <el-table-column label="全选"
                             align="center"
                             prop="apply"
                             width="55">
              <template slot="header"
                        slot-scope="scope">
                <el-checkbox v-model="checkAll"
                             :indeterminate="tableIsIndeterminate"
                             @change="handleChange"></el-checkbox>
              </template>
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.apply"
                             :true-label="1"
                             :false-label="0"
                             @change="tableCheckboxChange(scope.row)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="设备名称"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name"
                          class="layout-input"
                          readonly="readonly"></el-input>
              </template>
            </el-table-column>

          </el-table>
        </el-form-item>
        <!-- 智能穿戴设备 E-->
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="modalClose">取 消</el-button>
        <el-button type="primary"
                   @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'configDialog',
    props: {
      dataObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
      getList: {
        type: Function,
        default: null
      }
    },
    data () {
      return {
        uploadImgUrl: this.api.file.upload,
        loading: false,
        isEdit: false, // 编辑是否可编辑
        // 全选标志
        checkAll: false,
        // 半选标志
        tableIsIndeterminate: false,
        title: '',
        currTypeIndex: 1,
        currTypeName: '',
        currChildTypeIndex: [],
        currChildTypeName: '',
        formModel: {
          serveId: '', // 推荐服务种类
          imageUrl: '', // 推荐服务种类
          sortNum: '', // 排序
          sonTypeIds: [] // 推荐子类
        },
        formRules: {
          serveId: [
            { required: true, message: '请选择推荐服务种类', trigger: 'change' }
          ],
          imageUrl: [
            { required: true, message: '请选上传图片', trigger: 'blur' }
          ],
          sortNum: [
            { required: true, type: 'number', message: '请输入排序', trigger: 'blur' }
          ]
        },
        typeList: [], // 推荐服务种类列表
        childTypeList: [], // 推荐子类列表
        tableData: [],
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      // 查询推荐服务种类
      async getTypeList () {
        const { data: res } = await this.post(this.api.patient.getPatientList, { range: 2 })
        if (res.code === '200') {
          let resData = res.object.map(({
            id,
            name
          }) => ({
            serveId: id,
            name
          }))
          this.typeList = resData
        }
      },
      // 选择推荐服务种类
      async changeType (val) {
        this.currTypeIndex = val
        let selectedObj = this.typeList.find((item) => {
          return item.serveId === val;
        });
        this.currTypeName = selectedObj.name
        // 根据推荐服务种类查询推荐子类
        // 1 健康风险（筛查）2 医院体检 3 私人医生 4 家庭医生 5 门诊快诊 6 智能穿戴设备
        if (val === 1) {
          this.tableData = []
          this.formModel.hospitalIds = []
          const { data: res } = await this.post(this.api.patient.getSonType, { name: this.currTypeName })
          if (res.code === '200') {
            let resData = res.object.map(({
              id,
              name
            }) => ({
              id,
              name
            }))
            this.childTypeList = resData
          }
        }
        // 3 私人医生 4 家庭医生
        if (val === 3 || val === 4) {
          this.formModel.sonTypeIds = []
          this.formModel.hospitalIds = []
          // 1 私人医生包 2 私人医生包
          let typeParmas = val === 3 ? 1 : 2
          const { data: res } = await this.post(this.api.patient.getPackages, { type: typeParmas })
          if (res.code === '200') {
            let resData = res.object.map(({
              apply,
              departmentName,
              doctorName,
              hospitalName,
              serveName,
              studioId
            }) => ({
              apply,
              departmentName,
              doctorName,
              hospitalName,
              sonServeId: studioId,
              serveName,
            }))
            this.tableData = resData
          }
        }
        // 2 医院体检 5 门诊快诊
        if (val === 2 || val === 5) {
          this.tableData = []
          this.formModel.sonTypeIds = []
          // 1为体检，2为快诊
          let typeParmas = val === 2 ? 1 : 2
          const { data: res } = await this.post(this.api.patient.getHospitals, { type: typeParmas })
          if (res.code === '200') {
            let resData = res.object.map(({
              name,
              hospitalId,
            }) => ({
              name,
              hospitalId
            }))
            this.childTypeList = resData
          }
        }
        // 6 智能穿戴设备
        if (val === 6) {
          this.formModel.sonTypeIds = []
          this.formModel.hospitalIds = []
          const { data: res } = await this.post(this.api.patient.getWearableDevices)
          if (res.code === '200') {
            let resData = res.object.map(({
              id,
              name
            }) => ({
              id,
              name
            }))
            this.tableData = resData
          }
        }
      },
      // 根据推荐服务种类查询 推荐子类、 推荐医院
      async changeChildType (item) {
        this.currChildTypeIndex = item
        this.getTableList()
      },
      // 根据推荐子类查询推荐服务表格列表
      async getTableList () {
        // 1 健康风险（筛查）
        if (this.currTypeIndex === 1) {
          const { data: res } = await this.post(this.api.patient.getServeSons, {
            serveName: this.currTypeName,
            sonTypeIds: this.currChildTypeIndex
          })
          if (res.code === '200') {
            let resData = res.object.map(({
              apply,
              id,
              serviceName,
              sonServeName,
            }) => ({
              apply,
              sonServeId: id,
              serviceName,
              sonServeName,
            }))
            this.tableData = resData
          }
        }
        // 根据医院查询门诊或快诊的具体的服务列表
        // 2 医院体检 5 门诊快诊
        if (this.currTypeIndex === 2 || this.currTypeIndex === 5) {
          let currType = this.currTypeIndex === 2 ? 1 : 2 // 1 为体检，2 为快诊
          const { data: res } = await this.post(this.api.patient.getPhysicalQuick, {
            type: currType,
            hospitalIds: this.currChildTypeIndex
          })
          if (res.code === '200') {
            let resData = res.object.map(({
              apply,
              id,
              hospitalId,
              hospitalName,
              serveName,
              type
            }) => ({
              apply,
              sonServeId: id,
              hospitalName,
              serveName,
              type
            }))
            this.tableData = resData
          }
        }


      },
      // 上传成功
      handleAvatarSuccess (response, file, fileList) {
        if (response.code === '200') {
          // 状态码为200时则上传成功
          this.formModel.imageUrl = response.object[0]
          this.$message.success('上传成功');
        } else {
          // 状态码不是200时上传失败 从列表中删除
          fileList.splice(fileList.indexOf(file), 1);
          this.$message.error(response.message);
        }
      },
      // 上传前的方法
      beforeAvatarUpload (file) {
        let types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/bmp']
        const isType = types.includes(file.type);
        const isLt10M = file.size / 1024 / 1024 < 10
        if (!isType) {
          this.$message.error('上传图片必须是JPG/JPEG/GIF/PNG/BMP 格式!');
          return isType
        }
        if (!isLt10M) {
          this.$message.error('上传图片大小不能超过 10MB!');
          return isLt10M
        }
      },
      // 保存服务
      submitForm () {
        let params = { recommendServeBeans: this.tableData, ...this.formModel }
        this.$refs.formRef.validate(async (valid) => {
          if (valid) {
            const { data: res } = await this.post(this.api.patient.addServe, params)
            if (res.code === '200') {
              this.$message.success('保存成功!')
              this.modalClose()
              this.$parent.getList()
            } else {
              this.$message.error(res.$message)
            }
          }
        })
      },

      // 全选或全不选
      handleChange (val) {
        if (val) {
          this.tableData.forEach(item => {
            item.apply = 1;
          });
          this.tableIsIndeterminate = false;
        } else {
          this.tableData.forEach(item => {
            item.apply = 0;
          });
          this.tableIsIndeterminate = false;
        }
      },
      /**
       * @name: 全选 checkbox部分选择
       * @event: change
       * 1、isAllTrue：checkAll为true，为全选标志，tableIsIndeterminate为false，半选标志不显示
       * 2、isAllFalse：checkAll为false，无标志，tableIsIndeterminate为false，半选标志不显示
       * 3、其他情况，为半选标志
       */

      tableCheckboxChange (val) {
        setTimeout(() => {
          let isAllTrue = this.tableData.every(item => item.apply === true);
          let isAllFalse = this.tableData.every(item => item.apply === false);
          if (isAllTrue) {
            this.tableIsIndeterminate = false;
            this.checkAll = true;
          } else if (isAllFalse) {
            this.tableIsIndeterminate = false;
            this.checkAll = false;
          } else {
            this.checkAll = false;
            this.tableIsIndeterminate = true;
          }
        }, 0);
      },
      // 查询详情
      async getDetail () {
        this.currTypeIndex = this.dataObj.id
        const { data: res } = await this.post(this.api.patient.getDetail, { serveId: this.dataObj.id })
        if (res.code === '200') {
          let resData = res.object
          this.formModel.serveId = resData.id
          this.formModel.imageUrl = resData.imageUrl
          this.formModel.sortNum = resData.sortNum

          // 1 健康风险（筛查）
          if (this.currTypeIndex === 1) {
            this.changeType(this.formModel.serveId) // 推荐子类
            this.tableData = resData.recommendServeBeans.map(({
              apply,
              sonServeId,
              sonServeName,
              sonTypeName
            }) => ({
              apply,
              sonServeId,
              sonServeName: sonTypeName,
              serviceName: sonServeName
            }))
            this.formModel.sonTypeIds = resData.recommendSonTypeBeans.map(item => item.sonTypeId)
          }
          // 3 私人医生 4 家庭医生
          if (this.currTypeIndex === 3 || this.currTypeIndex === 4) {
            this.tableData = resData.recommendServeBeans.map(({
              apply,
              sonServeId,
              departmentName,
              doctorName,
              hospitalName,
              sonServeName
            }) => ({
              apply,
              sonServeId,
              departmentName,
              doctorName,
              hospitalName,
              serveName: sonServeName
            }))
          }
          // 2 医院体检 5 门诊快诊
          if (this.currTypeIndex === 2 || this.currTypeIndex === 5) {
            this.changeType(this.formModel.serveId) // 回显推荐医院
            this.tableData = resData.recommendServeBeans.map(({
              apply,
              hospitalName,
              sonServeName,
              hospitalId,
              type,
              sonServeId
            }) => ({
              apply,
              hospitalName,
              serveName: sonServeName,
              hospitalId,
              type,
              sonServeId
            }))
            this.formModel.sonTypeIds = resData.recommendSonTypeBeans.map(item => item.sonTypeId)
          }
          // 6 智能穿戴设备
          if (this.currTypeIndex === 6) {
            this.tableData = resData.recommendServeBeans.map(({
              apply,
              sonServeId,
              sonServeName
            }) => ({
              apply,
              sonServeId,
              name: sonServeName
            }))
          }
          let newArr = [...new Set(this.tableData.map(v => v.apply))]
          newArr.length > 1 ? this.tableIsIndeterminate = true : newArr[0] === 0 ? this.checkAll = false : this.checkAll = true
        }
      }
    },
    created () {
      this.getTypeList() // 查询推荐服务种类
      if (this.dataObj) {
        this.title = '编 辑'
        this.getDetail() // 查询详情
        this.isEdit = true
      } else {
        this.title = '新 增'
        this.isEdit = false
      }
    }
  }
</script>
<style scoped lang="scss">
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .layout-input {
    /deep/ .el-input__inner {
      border: 0 none !important;
      background: none;
    }
  }
</style>